import "../sass/detail.scss";

import { useState, useEffect } from "react";
import { CartO, LikeO } from "@react-vant/icons";
import { ActionBar } from "react-vant";

import { useParams, useNavigate } from "react-router-dom";

import { useSelector, useDispatch } from "react-redux";

import {
    changeCount,
    changeIsLoadShopbagCount,
} from "../store/store";

import axios from "axios";

import { Toast, NavBar } from "react-vant";

function Detail() {
    let shopbagCount = useSelector(
        (state) => state.publicModule.count
    );

    let isLoadShopbagCount = useSelector(
        (state) => state.publicModule.isLoadShopbagCount
    );

    let dispatch = useDispatch();

    //截取路由参数
    let params = useParams();
    //

    let navigate = useNavigate();

    //商品详情数据
    let [detailData, setDetailData] = useState({
        desc: [],
        rule: [],
    });

    //选择数量
    let [count, setCount] = useState(1);

    //收藏
    let [like, setLike] = useState(false);

    //根据商品pid获取商品详情数据
    let getDetailByPid = (pid) => {
        axios({
            method: "get",
            url: "/productDetail",
            params: {
                pid,
            },
        })
            .then((res) => {
                if (res.data.code === 600) {
                    let data = res.data.result[0];

                    data.desc = data.desc.split(/\n/);

                    //处理规格数据
                    let ruleKey = [
                        "cream",
                        "milk",
                        "sugar",
                        "tem",
                    ];

                    let rule = [];

                    ruleKey.forEach((item) => {
                        //如果规格不存在, 则无需处理
                        if (!data[item]) {
                            return;
                        }

                        let currentRule = {
                            title: data[`${item}_desc`],
                            activeIndex: 0,
                            rule: [],
                        };

                        let r = data[item].split(/\//);
                        r.forEach((v) => {
                            currentRule.rule.push({
                                title: v,
                            });
                        });

                        rule.push(currentRule);
                    });

                    data.rule = rule;

                    setDetailData(data);
                }
            })
            .catch((err) => {});
    };

    //修改选择数量
    let updateCount = (value) => {
        let c = count + value;

        if (c > 0) {
            setCount(c);
        }
    };

    //选择规格
    let selectRule = (item, i) => {
        if (item.activeIndex === i) {
            return;
        }

        item.activeIndex = i;

        setDetailData({ ...detailData });
    };

    //收藏商品
    let shoucang = () => {
        let url = "";
        if (like) {
            url = "/notlike";
        } else {
            url = "/like";
        }
        axios({
            method: "post",
            url,
            data: {
                pid: params.pid,
            },
        })
            .then((res) => {
                console.log("res", res);
                if (res.data.code === 700) {
                    return navigate("/login");
                }

                //收藏成功

                if (res.data.code === 800) {
                    Toast({
                        message: res.data.msg,
                    });
                    setLike(true);
                } else if (
                    res.data.code === 900 &&
                    res.data.result === 1
                ) {
                    //取消收藏
                    Toast({
                        message: res.data.msg,
                    });
                    setLike(false);
                }
            })
            .catch((err) => {
                // setLike(false);
            });
    };

    //加入购物袋
    let addShopbag = () => {
        //获取商品规格
        let rule = [];
        detailData.rule.forEach((item) => {
            let r = item.rule[item.activeIndex].title;
            rule.push(r);
        });

        axios({
            method: "post",
            url: "/addShopcart",
            data: {
                pid: params.pid,
                count,
                rule: rule.join("/"),
            },
        })
            .then((res) => {
                setTimeout(() => {
                    Toast({
                        message: res.data.msg,
                    });
                }, 350);

                if (res.data.code === 700) {
                    return navigate("/login");
                }

                if (res.data.code === 3000) {
                    //修改页面显示的购物袋数量
                    //
                    dispatch(
                        changeCount(shopbagCount + count)
                    );
                }
            })
            .catch((err) => {});
    };

    //如果用户登录, 则获取购物袋商品数量
    let getShopbagCount = () => {
        axios({
            method: "get",
            url: "/shopcartCount",
        })
            .then((res) => {
                if (res.data.code === 700) {
                    //未登录
                    dispatch(changeCount(0));
                    dispatch(
                        changeIsLoadShopbagCount(false)
                    );
                } else if (res.data.code === 4000) {
                    dispatch(changeCount(res.data.result));
                    dispatch(
                        changeIsLoadShopbagCount(true)
                    );
                }
            })
            .catch((err) => {});
    };

    //查询商品是否收藏
    let getcang = () => {
        let pid = params.pid;
        axios({
            method: "get",
            url: "/findlike",
            params: {
                pid,
            },
        })
            .then((res) => {
                console.log(res);
                if (
                    res.data.code === 1000 &&
                    res.data.result.length > 0
                ) {
                    setLike(true);
                }
            })
            .catch((err) => {});
    };

    useEffect(() => {
        getDetailByPid(params.pid);

        if (!isLoadShopbagCount) {
            getShopbagCount();
        }
        getcang();
    }, []);

    return (
        <div className="detail">
            <NavBar
                title={detailData.name}
                leftText="返回"
                onClickLeft={() => {
                    navigate(-1);
                }}
            />

            <div>
                <div>
                    <img
                        className="auto-img"
                        src={detailData.large_img}
                        alt=""
                    />
                </div>
                <div className="xianei">
                    <div className="shang">
                        <div className="zhuname">
                            {detailData.name}
                        </div>
                        <div className="yiname">
                            {detailData.enname}
                        </div>
                        <div className="jia">
                            &yen;{detailData.price}
                        </div>
                    </div>
                    <div className="guige">
                        {detailData.rule.map(
                            (item, index) => {
                                return (
                                    <div
                                        key={index}
                                        className="r-item"
                                    >
                                        <span className="pazhu">
                                            {item.title}
                                        </span>
                                        <span>
                                            {item.rule.map(
                                                (v, i) => {
                                                    return (
                                                        <span
                                                            className={`r ${
                                                                item.activeIndex ===
                                                                i
                                                                    ? "active"
                                                                    : ""
                                                            }`}
                                                            key={
                                                                i
                                                            }
                                                            onClick={() => {
                                                                selectRule(
                                                                    item,
                                                                    i
                                                                );
                                                            }}
                                                        >
                                                            {
                                                                v.title
                                                            }
                                                        </span>
                                                    );
                                                }
                                            )}
                                        </span>
                                    </div>
                                );
                            }
                        )}
                    </div>

                    <div className="xuan">
                        <div>选择数量</div>
                        <div className="anniu">
                            <div
                                className="zineione"
                                onClick={() => {
                                    updateCount(-1);
                                }}
                            >
                                -
                            </div>
                            <span className="co-ont">
                                {count}
                            </span>
                            <div
                                className="zineitwo"
                                onClick={() => {
                                    updateCount(1);
                                }}
                            >
                                +
                            </div>
                        </div>
                    </div>

                    <div className="miao">
                        <div>商品描述</div>
                        <div>
                            {detailData.desc.map(
                                (item, index) => {
                                    return (
                                        <p key={index}>
                                            {index + 1}.
                                            {item}
                                        </p>
                                    );
                                }
                            )}
                        </div>
                    </div>
                </div>
            </div>

            <div className="bottom-nav">
                <div className="demo-action-bar">
                    <ActionBar>
                        <ActionBar.Icon
                            icon={
                                <LikeO
                                    color={
                                        like
                                            ? "red"
                                            : "black"
                                    }
                                />
                            }
                            badge={{ dot: false }}
                            text={
                                like ? "取消收藏" : "收藏"
                            }
                            onClick={() => {
                                shoucang();
                            }}
                        />

                        <ActionBar.Icon
                            icon={<CartO />}
                            badge={{
                                content:
                                    shopbagCount > 0
                                        ? shopbagCount
                                        : "",
                            }}
                            text="购物车"
                            onClick={() => {
                                navigate("/shopbag");
                            }}
                        />

                        <ActionBar.Button
                            type="warning"
                            text="加入购物车"
                            onClick={() => {
                                addShopbag();
                            }}
                        />
                    </ActionBar>
                </div>
            </div>
        </div>
    );
}

export default Detail;
